﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 数组模拟栈
{
    class Program
    {
        static void Main(string[] args)
        {
            Push(1);
            Push(2);
            Push(3);
            Push(4);
            Push(5);
            Push(6);
            Push(7);
            Push(8);

            Console.WriteLine(Pop());
            Console.WriteLine(Pop());
            Console.WriteLine(Pop());

            Push(11);
            Push(12);
            Console.WriteLine(Pop());
            Console.WriteLine(Pop());
            Console.WriteLine(Pop());
            Console.WriteLine(Pop());
        }

        // 定义一个长度是5的int类型的数组
        static int[] a = new int[5];
        static int index = 0;//栈顶

        //入栈
        static void Push(int n)
        {
            // 如果数组满了，那么要扩容
            if (index == a.Length)
            {
                int[] b = new int[a.Length + 5];
                // 将a数组里面的值克隆到b数组
                Array.Copy(a, b, a.Length);
                // 再将b的值赋给a
                a = b;
            }
            
            a[index] = n;
            index++;
        }
        //出栈
        static int Pop()
        {
            if (index > 0)
            {
                index--;
                return a[index];
            }
            else
            {
                return 0;
            }
        }
    }
}
